package com.example.annotationcompiler;

import com.example.annotation.BindPath;
import com.google.auto.service.AutoService;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedOptions;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;

/**
 * *******************************************************
 * Author: chinadragon
 * Time: 2023/8/13 16:40
 * Name:
 * Overview:
 * Usage:
 * apt 不能在编译时修改代码，asm在编译时可以修改代码
 * *******************************************************
 */

//javac 知道处理
@AutoService(Processor.class)
@SupportedOptions(value = "MODULE_NAME")// MODULE_NAME 和 build.gradle里 javaCompileOptions 的名称一样
public class AnnotationCompiler extends AbstractProcessor {

    // 准备工作
    //生成代码的工具
    Filer mFiler;
    private String moduleName;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        mFiler = processingEnvironment.getFiler();
        System.out.println("== 执行了  AnnotationCompiler init");
        Map<String, String> options = processingEnvironment.getOptions();
        moduleName = options.get("MODULE_NAME");
        System.out.println("moduleName: "+moduleName);
    }

    //处理哪个注解
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> types = new HashSet<>();
        types.add(BindPath.class.getCanonicalName());
        System.out.println("== 执行了  AnnotationCompiler getSupportedAnnotationTypes");

        return types;
    }

    //支持哪个JDK版本

    @Override
    public SourceVersion getSupportedSourceVersion() {
        System.out.println("== 执行了  AnnotationCompiler getSupportedSourceVersion");

        //processingEnv来自父类AbstractProcessor
        return processingEnv.getSourceVersion();//支持最新版本
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        if (!set.isEmpty()) {
            Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindPath.class);
            generatedClass(elements);
            return true;
        }

        return false;

    }


    private void generatedClass(Set<? extends Element> routeElements){
        StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("package com.example.utill;\n");//包名
        sBuffer.append("import com.example.arouter.ARouter;\n");
        sBuffer.append("import com.example.arouter.IRouter;\n");
        sBuffer.append("import java.util.Map;\n");
        sBuffer.append("import android.app.Activity;\n");

        for (Element routeElement : routeElements) {
            //分类 login、 home、mine
            TypeElement typeElement = (TypeElement) routeElement;//分类
            String activityName = typeElement.getQualifiedName().toString();//类名
            sBuffer.append("import ");
            sBuffer.append(activityName);
            sBuffer.append(";\n");
        }

        //类
        sBuffer.append("public class ");
        sBuffer.append(moduleName);
        sBuffer.append("Router implements IRouter{\n");
        sBuffer.append("@Override\n");
        sBuffer.append("public void putActivity(Map<String, Class<? extends Activity>> routes){\n");


        for (Element element : routeElements) {
            //获得注解
            BindPath route = element.getAnnotation(BindPath.class);
            //函数体 paths.put(xx,xx.class)
            sBuffer.append("routes.put(\"");
            sBuffer.append(route.value());
            sBuffer.append("\",");
            sBuffer.append(element.getSimpleName());
            sBuffer.append(".class);\n");
        }


        sBuffer.append("}\n");
        sBuffer.append("}");


        try {
            //创建 Java文件
            JavaFileObject sourceFile = mFiler.createSourceFile("com.example.util." + moduleName +
                    "Router");
            //输出字符串
            OutputStream outputStream = sourceFile.openOutputStream();
            outputStream.write(sBuffer.toString().getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

//    @Override
//    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//        System.out.println("== 执行了  AnnotationCompiler process");
//
//        //LoginActivity 是 elements
//        Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindPath.class);
//        Map<String, String> map = new HashMap<>();
//        for (Element element : elements) {
//            //分类 login、 home、mine
//            TypeElement typeElement = (TypeElement) element;//分类
//            String activityName = typeElement.getQualifiedName().toString();//类名
//
//            //login/LoginActivity
//            String key = typeElement.getAnnotation(BindPath.class).value();
//            map.put(key, activityName + ".class");
//
//        }
//
//        //写文件
//        if (map.size() > 0) {
////            String className = "ActivityUtil" + System.currentTimeMillis();
//            String className = "ActivityUtil" + moduleName;
//            Writer writer = null;
//            try {
//                writer = mFiler.createSourceFile("com.example.util." + className).openWriter();
//                StringBuffer sBuffer = new StringBuffer();
//                sBuffer.append("package com.example.utill;\n");//包名
//                sBuffer.append("import com.example.arouter.ARouter;\n");
//                sBuffer.append("import com.example.arouter.IRouter;\n");
//                sBuffer.append("public class " + className + " implements IRouter {\n");
//                sBuffer.append("@Override\n");
//                sBuffer.append("public void putActivity() {\n");
//                Iterator<String> iterator = map.keySet().iterator();
//                while (iterator.hasNext()) {
//                    String key = iterator.next();
//                    String activityName = map.get(key);
//                    sBuffer.append("ARouter.getInstance().addActivity(\"" + key + "\"," + activityName + ");");
//                }
//
//                sBuffer.append("\n}\n}");
//                writer.write(sBuffer.toString());
////                writer.flush();
//                writer.close();//注意这里一定要关闭，否则build目录里javac 里没有 com.testcompont.util  或者 build目录里 generated -> ap_generated_sources 里的 activit是空的
//
//                //生成的代码 在 编译后在每个module的build目录里javac 里找到 com.testcompont.util 里 或者 build目录里 generated -> ap_generated_sources
//            } catch (IOException e) {
//                e.printStackTrace();
//                System.out.println("== 执行了  AnnotationCompiler process 异常信息：" + e.toString());
//
//            }
//        }
//
//        return false;
//    }
}
